<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/9/1
 * Time: 8:51
 */
namespace app\common\model;
use think\Model;
use think\Db;

class Help extends Model
{

    //获取请求头
    public function em_getallheaders()
    {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }

    //获取后缀
    public function getSuffix($picname){
        $pos = strrpos($picname,'.');
        $suffix = substr($picname,$pos+1);
        return $suffix;
    }

    //创建文件夹
    public function create_dir($path){
        $date=date('Ymd');
        if(!file_exists($path.$date)){
            mkdir($path.$date,0777,true);
        }
        $path = $path.$date.'/';
        return $path;
    }

    /**
     * 将对象转换成数组
     * @param $obj
     * @return mixed
     */
    public function object_to_array($obj){
        $arr = [];
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach ($_arr as $key=>$val){
            $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
            $arr[$key] = $val;
        }
        return $arr;
    }

    //php请求网络的方法
    public function curl_request($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

    //数组化简
    public  function row_array($result){
        if(!empty($result)){
            if(!empty($result[0])){
                return $result[0];
            }else{
                return null;
            }
        }else{
            return null;
        }
    }



    /**
     * 图片压缩处理
     * 原图路径  保存路径  目标宽度  目标高度
     */
    public function resize_image($source_path,$target_path,$imgWidth,$imgHeight){
        $source_info = getimagesize($source_path);
        $source_mime = $source_info['mime'];
        switch ($source_mime)
        {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }
        $target_image = imagecreatetruecolor($imgWidth,$imgHeight);//创建一个彩色的底图
        imagecopyresampled($target_image,$source_image,0,0,0,0,
            $imgWidth,$imgHeight,$source_info[0],$source_info[1]);
        //保存图片到本地
        $dir = $target_path;
        if(!is_dir($dir)){
            mkdir($dir,0777);
        }

        $fileName = $dir.date("YmdHis").uniqid().'.jpg';
        if(!imagejpeg($target_image,'./'.$fileName)){
            $fileName = '';
        }

        imagedestroy($target_image);

        return $fileName;

    }

    //创建头像
    public function create_heading($id,$head_img){
        $path 			  = $this->create_dir('uploads/user/');
        $this->put_file_from_url_content($head_img,"head_".$id.".jpg",$path);
        $data['path']	  = $path."head_".$id.".jpg";
        return $data['path'];
    }

    /**
     * 异步将远程链接上的内容(图片或内容)写到本地
     * @param unknown $url  远程地址
     * @param unknown $saveName 保存在服务器上的文件名
     * @param unknown $path 保存路径
     * @return boolean
     */
    private function put_file_from_url_content($url, $saveName, $path) {
        set_time_limit ( 0 );  							   // 设置运行时间为无限制
        $url = trim ( $url );
        $curl = curl_init (); 							   // 设置你需要抓取的URL
        curl_setopt ( $curl, CURLOPT_URL, $url );  		   // 设置header
        curl_setopt ( $curl, CURLOPT_HEADER, 0 );  		   // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );  // 运行cURL，请求网页
        $file = curl_exec ( $curl ); 					   // 关闭URL请求
        curl_close ( $curl );  							   // 将文件写入获得的数据
        $filename = $path . $saveName;
        $write = @fopen ( $filename, "w" );
        if ($write == false) {
            return false;
        }
        if (fwrite ( $write, $file ) == false) {
            return false;
        }
        if (fclose ( $write ) == false) {
            return false;
        }
    }

    //生成海报二维码
    public function qr_create($id=5,$table='store_member',$qrset_id=1){
        $list = Db::table($table)->where("id=$id")->find();

        $head_img = $this->create_heading($id,$list['headimg']);


        $erweima_img = $list['qrcode'];

        $table_id = 0;
        $list_id = $list['id'];
        $phone = Db::table("store_member_twitter")->where(['u_id'=>$list['id']])->value('phone');


        $info = Db::query("select * from store_wx_qrset where id=$qrset_id");
        $erweima_height = $erweima_width = $info[0]['qr_size'];
        $dst_path = $info[0]['pic_url'];
        $head_height = $head_width = $info[0]['head_size'];

        $getSuffix = $this->getSuffix($dst_path);

        $str = $list['nickname'];
        $pic = $list_id.'_'.$table_id;

        $src = $this -> img_suo($erweima_img, $erweima_width, $erweima_height,$getSuffix);

        $dst = imagecreatefromstring(file_get_contents($dst_path));
        imagecopymerge($dst, $src, $info[0]['qr_x'], $info[0]['qr_y'], 0, 0, $erweima_width, $erweima_height, 100);

        $src1 = $this -> img_suo($head_img, $head_width, $head_height,'');

        imagecopymerge($dst, $src1, $info[0]['head_x'], $info[0]['head_y'], 0, 0, $head_width, $head_height, 100);

        $font_size = $info[0]['font_size'];
        $fnt_x = $info[0]['font_x'];
        $fnt_y = $info[0]['font_y'];
        $fnt = dirname(__FILE__) .'/msyh.ttf';
        $black = imagecolorallocate($dst, 50, 50, 50);

        $fontBox=imagettfbbox($font_size, 0, $fnt, $str); //磅
        $fontwith=abs($fontBox[2]-$fontBox[0]);

        switch($getSuffix)
        {
            case "png":
                $beijing=imagecreatefrompng($dst_path);
                break;

            case "jpeg":
                $beijing=imagecreatefromjpeg($dst_path);
                break;

            case "gif":
                $beijing=imagecreatefromgif($dst_path);
                break;
        }


        $jobx=abs((imagesx($beijing)-$fontwith)/2); //居中是 $jobx-$fntx

        $content = $str;
        imagettftext($dst,$font_size,0,$fnt_x,$fnt_y,$black,$fnt,$content);     //居中

        $content1 = $phone;
        imagettftext($dst,$font_size,0,$fnt_x,$fnt_y+130,$black,$fnt,$content1);     //居中


        $path = $this->create_dir("uploads/$table/");
        imagejpeg($dst, $path . $pic . '.jpg');
        imagedestroy($dst);

        return sysconf('realm_name').'/'. $path . $pic . '.jpg';
    }



    //缩略图
    function img_suo($img = 'head.jpg', $new_width = 500, $new_height = 500,$getSuffix=''){
        list($width, $height) = getimagesize($img);
        $image_p = imagecreatetruecolor($new_width, $new_height);

        if($getSuffix=='png'){
            $image = imagecreatefrompng($img);
        }else{
            $image = imagecreatefromjpeg($img);
        }

        if($getSuffix==''){
            $image = @imagecreatefromjpeg($img);
            if(empty($image)){
                $image = @imagecreatefrompng($img);
            }
        }

        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        return $image_p;
    }


    //生成海报文字
    public function yinxiang_create($id,$table,$qrset_id){
        $list = Db::table($table)->where("id=$id")->find();
        $list_id = $list['sn'];

        $list_sn = str_split($list['sn']);
        $list_sn = join(' ',$list_sn);


        $str = 0;
        $pic = $list_id.'_'.$str;

        $info = Db::query("select * from store_wx_qrset where id=$qrset_id");
        $dst_path = $info[0]['pic_url'];
        $dst = imagecreatefromstring(file_get_contents($dst_path));

        $font_size = $info[0]['font_size'];
        $fnt_x = $info[0]['font_x'];
        $fnt_y = $info[0]['font_y'];
        $fnt = dirname(__FILE__) .'/msyh.ttf';
        $black = imagecolorallocate($dst, 0, 0, 0);

        $fontBox=imagettfbbox($font_size, 0, $fnt, $list_sn); //磅
        $fontwith=abs($fontBox[2]-$fontBox[0]);


        $getSuffix = $this->getSuffix($dst_path);

        switch($getSuffix)
        {
            case "png":
                $beijing=imagecreatefrompng($dst_path);
                break;

            case "jpeg":
                $beijing=imagecreatefromjpeg($dst_path);
                break;

            case "jpg":
                $beijing=imagecreatefromjpeg($dst_path);
                break;

            case "gif":
                $beijing=imagecreatefromgif($dst_path);
                break;
        }


        $jobx=abs((imagesx($beijing)-$fontwith)/2);

        $content = 'SN码 : '.$list_sn;
        imagettftext($dst,$font_size,0,$jobx-$fnt_x,$fnt_y,$black,$fnt,$content);     //居中


        $path = $this->create_dir("storage/$table/");
        imagejpeg($dst, $path . $pic . '.jpg');
        imagedestroy($dst);

        return sysconf('realm_name').'/'. $path . $pic . '.jpg';
    }


    //生成海报二维码
    public function qr_create_sn($id=1,$table="shop_pay_sn_two",$qrset_id=8){
        $list = Db::table($table)->where("id=$id")->find();
        $erweima_img = $list['qrcode'];
        $erweima_img = 'https://e.shimeng.net.cn/static/theme/img/ceshi.png';

        $table_id = 0;
        $list_id = $list['id'];
        $list_sn = $list['sn'];


        $info = Db::query("select * from store_wx_qrset where id=$qrset_id");
        $erweima_height = $erweima_width = $info[0]['qr_size'];
        $dst_path = $info[0]['pic_url'];

        $getSuffix = $this->getSuffix($dst_path);

        $str = $table_id;
        $pic = $list_id.'_'.$str;

        $src = $this -> img_suo($erweima_img, $erweima_width, $erweima_height,$getSuffix);

        $dst = imagecreatefromstring(file_get_contents($dst_path));
        imagecopymerge($dst, $src, $info[0]['qr_x'], $info[0]['qr_y'], 0, 0, $erweima_width, $erweima_height, 100);



        $font_size = $info[0]['font_size'];
        $fnt_x = $info[0]['font_x'];
        $fnt_y = $info[0]['font_y'];
        $fnt = dirname(__FILE__) .'/msyh.ttf';
        $black = imagecolorallocate($dst, 50, 50, 50);

        $fontBox=imagettfbbox($font_size, 0, $fnt, $str); //磅
        $fontwith=abs($fontBox[2]-$fontBox[0]);

        switch($getSuffix)
        {
            case "png":
                $beijing=imagecreatefrompng($dst_path);
                break;

            case "jpeg":
                $beijing=imagecreatefromjpeg($dst_path);
                break;

            case "gif":
                $beijing=imagecreatefromgif($dst_path);
                break;
        }


        $jobx=abs((imagesx($beijing)-$fontwith)/2);

        $content = 'SN: '.$list_sn;
        imagettftext($dst,$font_size,0,$jobx-$fnt_x,$fnt_y,$black,$fnt,$content);     //居中


        $path = $this->create_dir("storage/qr_create_sn/");
        imagejpeg($dst, $path . $pic . '.jpg');
        imagedestroy($dst);

        echo sysconf('realm_name').'/'. $path . $pic . '.jpg';
    }


}